package com.hui.platform.falseworkapi.service.base.oss.controller;


import com.hui.platform.falseworkapi.common.web.annotation.ApiResult;
import com.hui.platform.falseworkapi.service.base.oss.constant.OssDirEnum;
import com.hui.platform.falseworkapi.service.base.oss.dto.FileInfo;
import com.hui.platform.falseworkapi.service.base.oss.dto.OssCallbackResult;
import com.hui.platform.falseworkapi.service.base.oss.dto.OssPolicyResult;
import com.hui.platform.falseworkapi.service.base.oss.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Oss相关操作接口
 * @author hui
 */
@RestController
@Api(tags = "OSS管理")
@ApiResult
@RequestMapping("/aliyun/oss")
@CrossOrigin
public class OssController {

    @Autowired
    private OssService ossService;

    @ApiOperation(value = "oss上传签名生成")
    @GetMapping("/policy")
    public OssPolicyResult policy() {
        return ossService.policy();
    }

    @ApiOperation(value = "删除oss文件")
    @PostMapping("/deleteFile")
    public Boolean deleteFile(String url) {
        return ossService.deleteFile(url);
    }

    @ApiOperation(value = "oss上传成功回调")
    @PostMapping("/callback")
    public OssCallbackResult callback(HttpServletRequest request) {
        return ossService.callback(request);
    }

    /**
     *文件上传
     * @param files 上传的文件
     * @return 标准结果集
     */
    @ApiOperation(value="文件上传",notes="请求方法：POST，文件上传")
    @PostMapping(path="/uploadFile")
    public List<FileInfo> uploadFile(@RequestParam("files") List<MultipartFile> files){
        try {
            List<FileInfo> fileInfos = new ArrayList<>();
            for (MultipartFile file : files){
                FileInfo fileInfo = new FileInfo();
                String fileName = file.getOriginalFilename();
                //OssDirEnum.FILE_DIR:指定上传的文件夹
                String url = ossService.uploadFile(fileName, file.getInputStream(), OssDirEnum.FILE_DIR);
                fileInfo.setFilename(fileName)
                        .setFileUrl(url.replace("n-internal", "n"))
                        .setFileSize(file.getSize()/1024L)
                        .setContentType(fileInfo.getContentType());
                fileInfos.add(fileInfo);
            }
            return fileInfos;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
